import os
import cv2
import numpy as np
import base64

def cv2_imread(path, mode=cv2.IMREAD_COLOR):
    """
    read image based on cv2 mode
    """
    img_read = cv2.imdecode(np.fromfile(path, dtype=np.uint8), mode)
    return img_read


def cv2_imwrite(path, img_write):
    """
    save image based on cv2 mode
    """
    suffix = os.path.splitext(path)[-1]
    cv2.imencode(suffix, img_write)[1].tofile(path)


def cv2_base64(image_np):
    image = cv2.imencode('.jpg',image_np)[1]
    image_code = str(base64.b64encode(image))[2:-1]
    return image_code


def base64_cv2(base64_code):
    img_data = base64.b64decode(base64_code)
    img_array = np.frombuffer(img_data, np.uint8)
    img = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)
    return img


def return_euclidean_distance(feature_1, feature_2):
    feature_1 = np.array(feature_1)
    feature_2 = np.array(feature_2)
    dist = np.sqrt(np.sum(np.square(feature_1 - feature_2)))
    # print("欧式距离: ", dist)
    if dist > 0.4:
        return "diff"
    else:
        return "same"


def save_cache(data, file_path):
    file = open(file_path, 'wb')
    pickle.dump(data, file)
    file.close()


def load_cache(file_path):
    data = dict()
    if os.path.isfile(file_path):
        file = open(file_path, 'rb')
        data = pickle.load(file)
        file.close()
    else:
        print('file not exist: ' + file_path)
    return data


if __name__ == '__main__':
    img_np = cv2_imread(r"C:\Users\admin\Documents\pie-face-recognition-system\backend\app\dataset\train_data\s1\1.jpg")
    print(cv2_base64(img_np))